package com.huaxia.util;



import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author wangli 爱我华夏，爱我中华！
 * @date 2021/03/15 11:17
 */
@Component
public class LoginManageInterceptor implements HandlerInterceptor{

    private static final Logger log = LoggerFactory.getLogger(LoginManageInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String token =  request.getHeader("Authorization");
        log.debug("请求携带的token---------------------->{}",token);

        if (token == null){
            // 设置401状态码
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            // 添加重定向的Location头
            response.setHeader("Location", "https://sd.ruiinsurance.com/web/#/pages/proposal/proposalJump?proposalId=1960229837138673664");
            return false;
        }else {
            List<Map<String, String>> headerList = new ArrayList<>();
            Map<String, String> ContentType = new HashMap<>();
            ContentType.put("key", "Content-Type");
            ContentType.put("value", "application/json;charset=UTF-8");
            headerList.add(ContentType);

            Map<String, String> Authorization = new HashMap<>();
            Authorization.put("key", "Authorization");
            Authorization.put("value", token);
            headerList.add(Authorization);
            JSONObject jsonObject = HttpRequestUtil.httpRequest(RuiConstant.getRuiDomain()+"/prod-api/getInfo", "GET", null, headerList);
            String code = jsonObject.getString("code");
            log.debug("向web发送请求，返回的状态码是code-------------->{}",code);
            if ("401".equals(code)){
                // 设置401状态码
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                // 添加重定向的Location头
                response.setHeader("Location", "https://sd.ruiinsurance.com/web/#/pages/proposal/proposalJump?proposalId=1960229837138673664");
                return false;
            }
        }
        return true;
    }
}
